define(function () {

  /**
   * [getTopLevels 获取第一级level]
   * @param  {Function} cb [description]
   * @return {[type]}      [description]
   */
  function getTopLevels(cb) {
    ajaxMethod({
      url: '/api/level/0/childs?status=1',
      success: function (data, status) {
        if(status.code == 0) {
          cb && cb(data)
        }
      }
    })
  }

  /**
   * [getAllLevels 获取level列表]
   * @param  {Function} cb [description]
   * @return {[type]}      [description]
   */
  function getAllLevels(cb) {
    ajaxMethod({
      url: '/api/levels?status=1',
      success: function (data, status) {
        if(status.code == 0) {
          cb && cb(data)
        }
      }
    })
  }

  /**
   * [addNode 添加节点]
   * @param {[type]}   treeId   [description]
   * @param {[type]}   treeNode [description]
   * @param {Function} cb       [description]
   */

  function createNode(treeId, treeNode, cb) {
    ajaxMethod({
      url: ' /api/level',
      method: 'post',
      data: {
        pid: treeNode.id,
        title: "new node"
      },
      success: function (data, status) {
        if(status.code == 0) {
          cb && cb(data)
        }
      }
    })
  }

  /**
   * [updateNode 更新节点]
   * @param {[type]}   treeId   [description]
   * @param {[type]}   treeNode [description]
   * @param {Function} cb       [description]
   */
  function updateNode(treeId, treeNode, newName, cb) {
    var flag = false
    ajaxMethod({
      url: '/api/level/' + treeNode.id,
      method: 'put',
      async: false,
      data: {
        pid: treeNode.pid,
        title: newName
      },
      success: function (data, status) {
        if(status.code == 0) {
          flag = true
          cb && cb(data)
        }
      }
    })
    return flag
  }

  /**
   * [deleteNode 删除节点]
   * @param  {[type]}   treeId   [description]
   * @param  {[type]}   treeNode [description]
   * @param  {Function} cb       [description]
   * @return {[type]}            [description]
   */
  function deleteNode(treeId, treeNode, cb) {
    var flag = false
    ajaxMethod({
      url: '/api/level/'+ treeNode.id +'/disable',
      method: 'put',
      async: false,
      success: function (data, status) {
        if(status.code == 0) {
          flag = true
          cb && cb(data)
        }
      }
    })
    return flag
  }



  function levelTree(config) {
    config || (config = {})

    var log, className = "dark";
    var idName = 'tree'

  	function beforeDrag(treeId, treeNodes) {
  		return false;
  	}

  	function beforeEditName(treeId, treeNode) {
  		className = (className === "dark" ? "":"dark");
  		showLog("[ "+getTime()+" beforeEditName ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
  		var zTree = $.fn.zTree.getZTreeObj(idName);
  		zTree.selectNode(treeNode);
      setTimeout(function() {
        zTree.editName(treeNode);
      }, 0);
  		return false;
  	}

  	function beforeRemove(treeId, treeNode) {
  		className = (className === "dark" ? "":"dark");
  		var zTree = $.fn.zTree.getZTreeObj(idName);
  		zTree.selectNode(treeNode);
  		var deleteFlag = confirm("确认删除节点 [" + treeNode.title + "] 吗？");
      if(deleteFlag) {
        return deleteNode(treeId, treeNode)
      }
      return false
  	}

  	function onRemove(e, treeId, treeNode) {
  		// showLog("[ "+getTime()+" onRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
  	}

  	function beforeRename(treeId, treeNode, newName, isCancel) {
  		className = (className === "dark" ? "":"dark");

  		if (newName.length == 0) {
        setTimeout(function () {
          var zTree = $.fn.zTree.getZTreeObj(idName)
  				zTree.cancelEditName();
  				alert("节点名称不能为空");
        },0)
        return false
      }

      if(treeNode.title == newName) {
        return true
      }

  		return updateNode(treeId, treeNode, newName)
  	}

  	function onRename(e, treeId, treeNode, isCancel) {

  		// showLog((isCancel ? "<span style='color:red'>":"") + "[ "+getTime()+" onRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>":""));
  	}

  	function showRemoveBtn(treeId, treeNode) {
  		return !treeNode.pid == 0
      // return true
  	}

  	function showRenameBtn(treeId, treeNode) {
  		// return !treeNode.isLastNode;
  		return true
  	}

  	function showLog(str) {
  		if (!log) log = $("#log");
  		log.append("<li class='"+className+"'>"+str+"</li>");
  		if(log.children("li").length > 8) {
  			log.get(0).removeChild(log.children("li")[0]);
  		}
  	}

  	function getTime() {
  		var now= new Date(),
  		h=now.getHours(),
  		m=now.getMinutes(),
  		s=now.getSeconds(),
  		ms=now.getMilliseconds();
  		return (h+":"+m+":"+s+ " " +ms);
  	}

  	function addHoverDom(treeId, treeNode) {
  		var sObj = $("#" + treeNode.tId + "_span");
  		if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;

      if(showAddBtnFlag == false) {
        return
      }

  		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
  			+ "' title='add node' onfocus='this.blur();'></span>";
  		sObj.after(addStr);
  		var btn = $("#addBtn_"+treeNode.tId);
  		if (btn) btn.bind("click", function(){

        createNode(treeId, treeNode, function (data) {
          var zTree = $.fn.zTree.getZTreeObj(idName);
    			zTree.addNodes(treeNode, data);
    			return false;
        })
        return false

  		});
  	};


  	function removeHoverDom(treeId, treeNode) {
  		$("#addBtn_"+treeNode.tId).unbind().remove();
  	};

  	function selectAll() {
  		var zTree = $.fn.zTree.getZTreeObj(idName);
  		zTree.setting.edit.editNameSelectAll =  $("#selectAll").attr("checked");
  	}

    function getDefined() {
      var ret;
      for (var i = 0, len = arguments.length; i < len; i++) {
        var cur = arguments[i]
        if(cur != undefined) {
          ret = cur;
          break;
        }
      }
      return ret
    }

    showRemoveBtn = getDefined(config.showRemoveBtn, showRemoveBtn) //remove显示规则 function
    showRenameBtn = getDefined(config.showRenameBtn, showRenameBtn) //rename显示规则 function
    showAddBtnFlag = getDefined(config.showAddBtnFlag, true) //addbtn 显示规则 boolean
    setCurNode = getDefined(config.setCurNode, false) // 设置当前节点
    setCheckNodes = getDefined(config.setCheckNodes, false) // 设置当前节点

    checkEnable = getDefined(config.checkEnable, false) // 开启check勾选

    var setting = {
      check: {
        enable: checkEnable,
        chkboxType: {"Y": "", "N": ""}
      },
  		view: {
  			addHoverDom: addHoverDom,
  			removeHoverDom: removeHoverDom,
  			selectedMulti: false
  		},
  		edit: {
  			enable: true,
  			editNameSelectAll: true,
  			showRemoveBtn: showRemoveBtn,
  			showRenameBtn: showRenameBtn
  		},
  		data: {
  			simpleData: {
  				enable: true,
    			idKey: "id",
    			pIdKey: "pid",
    			rootPId: 0
  			},
        key: {
          name: 'title'
        }
  		},
  		callback: {
  			beforeDrag: beforeDrag,
  			beforeEditName: beforeEditName,
  			beforeRemove: beforeRemove,
  			beforeRename: beforeRename,
  			onRemove: onRemove,
  			onRename: onRename
  		}
  	};

    getAllLevels(function (zNodes) {
      $.each(zNodes, function (i, item) {
        item.open = true
        item.chcked = true
      })

      $.fn.zTree.init($("#"+idName), setting, zNodes);
      $("#selectAll").bind("click", selectAll);

      if(setCurNode) {
        setCurNode(idName)
      }

      if(setCheckNodes) {
        setCheckNodes(idName)
      }
    })

  }

  window.levelTree = levelTree
  return levelTree
})
